package com.simemg.reader.fraction.novel;

import com.simemg.reader.ResourceTable;
import com.simemg.reader.provider.PageListProvider;
import com.simemg.reader.slice.NovelSlice;
import com.simemg.reader.store.Book;
import com.simemg.reader.store.Page;
import com.simemg.reader.utils.RouterUtil;
import com.simemg.reader.utils.StoreUtil;
import ohos.aafwk.ability.fraction.Fraction;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class IndexFraction extends Fraction {
    private boolean isDec = false;
    private final NovelSlice slice;

    private ListContainer pageListContainer;
    private PageListProvider pageListProvider;
    private RadioContainer sortContainer;
    private Text count;

    private final List<Page> pageList = new ArrayList<>();


    public IndexFraction(NovelSlice slice) {
        this.slice = slice;
    }

    protected Component onComponentAttached(LayoutScatter scatter, ComponentContainer container, Intent intent) {
        return scatter.parse(ResourceTable.Layout_slice_index, container, false);
    }

    @Override
    protected void onActive() {
        super.onActive();

        initComponent();
        loadData();
        addComponentListen();
    }

    void initComponent(){
        pageListContainer = (ListContainer)getComponent().findComponentById(ResourceTable.Id_page_list);
        pageListProvider = new PageListProvider(pageList, this);
        pageListContainer.setItemProvider(pageListProvider);

        sortContainer = (RadioContainer) getComponent().findComponentById(ResourceTable.Id_sort);
        count = (Text) getComponent().findComponentById(ResourceTable.Id_count);

    }

    void loadData() {
        pageList.clear();
        List<Page> list = StoreUtil.searchPageList(slice.getBook());
        pageList.addAll(list);
        pageListProvider.notifyDataChanged();
        pageListProvider.setNum(slice.getBook().getNowNum());
        pageListContainer.scrollToCenter(Math.max(slice.getBook().getNowNum() - 8, 0));
        count.setText("总共"+ pageList.size());
    }

    void addComponentListen() {
        pageListContainer.setItemClickedListener((listContainer, component, i, l) -> {

        });

        sortContainer.setMarkChangedListener((radioContainer, i) -> {
            if (i == 0 && isDec) {
                Collections.reverse(pageList);
                pageListProvider.notifyDataChanged();
                isDec = false;
            }
            if(i == 1 && !isDec) {
                Collections.reverse(pageList);
                pageListProvider.notifyDataChanged();
                isDec = true;
            }
        });
    }
}
